package com.leyou.upload.service;

import com.aliyun.oss.OSS;
import com.aliyun.oss.common.utils.BinaryUtil;
import com.aliyun.oss.model.MatchMode;
import com.aliyun.oss.model.PolicyConditions;
import com.leyou.common.enums.ExceptionEnum;
import com.leyou.common.exceptions.LyException;
import com.leyou.upload.config.OSSProperties;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.*;

/**
 * @package com.leyou.upload.web
 * @description: 上传服务的业务层
 * @author: 许超越
 * @date 2019/6/25 16:55
 * @version: V1.0
 */
@Service
@Slf4j
public class UploadService {

    //设置上传文件支持的类型
    private static final List<String> ALLOW_IMAGE_TYPES = Arrays.asList("image/png", "image/jpeg", "image/bmp", "image/jpg");
    //创建一个保存上传图片的文件夹路径
    private static final String IMAGE_DIR = "F:\\javaTool\\nginx-1.14.0\\html\\images";
    //创建返回值得公共路径
    private static final String IMAGE_URL = "http://image.leyou.com/images/";

    /**
     * 新增商品出的图片logo上传
     *
     * @return
     * @param: file 上传的文件
     */
    public String uploadImage(MultipartFile file) {
        //1.图片信息校验
        //1)图片文件类型的校验
        if (!ALLOW_IMAGE_TYPES.contains(file.getContentType())) {
            throw new LyException(ExceptionEnum.INVALID_FILE_TYPE);
        }
        //2)校验上传图片的内容
        BufferedImage image = null;
        try {
            image = ImageIO.read(file.getInputStream());
            if (null == image) {
                throw new RuntimeException();
            }
        } catch (Exception e) {
            throw new LyException(ExceptionEnum.INVALID_FILE_TYPE, e);
        }
        //2.文件的存储地址
        //获取源文件的扩展名
        String extensionName = StringUtils.substringAfterLast(file.getOriginalFilename(), ".");
        //为上传的文件创建一个名词
        String filename = UUID.randomUUID().toString().replaceAll("-", "") + "." + extensionName;
        //3.保存文件
        try {
            file.transferTo(new File(IMAGE_DIR, filename));
        } catch (IOException e) {
            //打印上传错误日志
            log.error("文件上传失败！原因：{}", e.getMessage(), e);
            throw new LyException(ExceptionEnum.FILE_UPLOAD_ERROR, e);
        }
        return IMAGE_URL + filename;
    }


    /**
     * 获取阿里OSS云服务的签名认证
     *
     * @return
     */

    @Autowired
    private OSSProperties prop;

    @Autowired
    private OSS client;


    public Map<String, Object> getAliSignature() {
        try {
            long expireTime = prop.getExpireTime();
            long expireEndTime = System.currentTimeMillis() + expireTime * 1000;
            Date expiration = new Date(expireEndTime);
            PolicyConditions policyConds = new PolicyConditions();
            policyConds.addConditionItem(PolicyConditions.COND_CONTENT_LENGTH_RANGE, 0, prop.getMaxFileSize());
            policyConds.addConditionItem(MatchMode.StartWith, PolicyConditions.COND_KEY, prop.getDir());

            String postPolicy = client.generatePostPolicy(expiration, policyConds);
            byte[] binaryData = postPolicy.getBytes("utf-8");
            String encodedPolicy = BinaryUtil.toBase64String(binaryData);
            String postSignature = client.calculatePostSignature(postPolicy);

            Map<String, Object> respMap = new LinkedHashMap<>();
            respMap.put("accessId", prop.getAccessKeyId());
            respMap.put("policy", encodedPolicy);
            respMap.put("signature", postSignature);
            respMap.put("dir", prop.getDir());
            respMap.put("host", prop.getHost());
            respMap.put("expire", expireEndTime);
            return respMap;
        } catch (Exception e) {
            throw new LyException(ExceptionEnum.UPDATE_OPERATION_FAIL);
        }
    }
}
